package main

import (
	"log"
	global2 "longmen/server/config/global"
	middleware2 "longmen/server/internal/rpc/middleware"
	"longmen/server/internal/rpc/tencentim/api"
	"longmen/server/internal/rpc/tencentim/room_event"
	"longmen/server/internal/rpc/tencentim/server"
	"longmen/server/pkg/common/app"
	"longmen/server/pkg/common/app/etcd"
	appServer "longmen/server/pkg/common/app/server"
	"longmen/server/pkg/common/helper/blackWorlds"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/redis/cache"
	"longmen/server/pkg/grpc_client"
	pb "longmen/server/pkg/protobuf"

	grpcrecovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	//grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
)

func main() {
	global2.Initialize("../../../config/app.properties")
	global2.InitPublisher()
	//设置aes加密key
	cache.SetAESKey()
	//初始化MQ
	global2.InitMQ()
	err := global2.InitElasticSearch()
	if err != nil {
		log.Fatalf("%s", err.Error())
	}
	global2.AppName = "webapi_rpc_tencent_im"
	grpc_client.InitGrpc()
	limit := middleware2.NewTencentImRequestLimit()

	//metrics := prometheus.NewGrpcMetrics()
	grpcSrv := appServer.New(
		appServer.Network("tcp"),
		appServer.Address(":"+global2.Config.GetString("grpc.tencent_im_server_port")),
		//appServer.StreamInterceptor(
		//	grpc_prometheus.StreamServerInterceptor,
		//),
		appServer.UnaryServerInterceptor(
			grpcrecovery.UnaryServerInterceptor(appServer.RecoveryOption()...),
			middleware2.TokenValid,
			limit.RequestLimit,
			//grpczap.UnaryServerInterceptor(global.ZapLogger),
			//metrics.GrpcMetrics.UnaryServerInterceptor(),
		),
	)
	//global2.Log.Info(global2.Config.GetInt("prometheus.tx_im.port"))

	grpcTencentImServer := &server.TencentIM{}
	pb.RegisterTencentImServiceServer(grpcSrv, grpcTencentImServer)
	app := app.NewApp(
		app.Version(global2.GetMicroserviceVersion()),
		app.Name(global2.GetMicroserviceName(_const.GRPC_TENCENT_IM_SERVER_NAME_KEY)),
		app.Register(etcd.NewEtcdRegister(global2.GetEtcdCli())),
		app.Server(grpcSrv),
	)
	//初始黑名单词库
	blackWorlds.LoopKeyWords()

	// 从配置文件读取是否开启WatchTimeStatWorkerPool以及worker数量
	enableWatchTimeStat := global2.Config.GetBool("tencent_im.enable_watch_time_stat")
	watchTimeStatWorkerNum := global2.Config.GetInt("tencent_im.watch_time_stat_worker_num")
	if enableWatchTimeStat && watchTimeStatWorkerNum > 0 {
		room_event.InitWatchTimeStatWorkerPool(watchTimeStatWorkerNum)
	}

	//metrics.StarHttpServer(grpcSrv, global2.Config.GetInt("prometheus.tx_im.port"))

	//pyroscope.InitPyroScope("tx_im")

	//crontab.ReplayChatClientHub = crontab.NewReplayChatHub()
	//crontab.ReplayChatClientHub.Run(context.Background())

	api.InitAPI()
	if err := app.Start(); err != nil {
		log.Fatalf("init account server is error: %+v \n", err)
	}
}
